package com.kanshu.ksgb.fastread.doudou.module.reader.presenter;


import android.util.Log;

import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.base.basemvp.RxPresenter;
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper;
import com.kanshu.ksgb.fastread.doudou.common.net.rx.BaseObserver;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.SimpleChapterBean;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.BookService;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ChapterRequestParams;

import org.reactivestreams.Subscription;

import java.util.HashSet;
import java.util.concurrent.TimeUnit;

import io.reactivex.ObservableTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subjects.Subject;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by newbiechen on 17-5-16
 */
public class ReadPresenter extends RxPresenter<ReadContract.View>
        implements ReadContract.Presenter {
    private BookService mBookService;
    public Subject<Integer> mLifeCyclerSubject;
    private static final String TAG = "ReadPresenter";
    private String mNovelSource;

    public ReadPresenter(String novelSource, Subject<Integer> mLifeCyclerSubject) {
        this.mLifeCyclerSubject = mLifeCyclerSubject;
        mNovelSource = novelSource;
        RetrofitHelper helper = RetrofitHelper.getInstance();
        mBookService = helper.createService(BookService.class);
    }

    public <T> ObservableTransformer<T, T> asyncRequest() {
        if (mLifeCyclerSubject == null) {
            return upstream -> upstream.subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread());

        } else {
            return upstream -> upstream.subscribeOn(Schedulers.computation())
                    .observeOn(AndroidSchedulers.mainThread())
                    .takeUntil(mLifeCyclerSubject);
        }
    }

    private Subscription mChapterSub;

    private String getContentIdKey(String contentId) {
        if (contentId == null) {
            contentId = "";
        }
        return "content_id_" + contentId;
    }

    private HashSet<String> mHashSet = new HashSet<>();

    @Override
    public void getChapterContent(ChapterRequestParams params, int loadType) {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            mView.showError(params.content_id, Constants.ErrCode.NetErr, "no net");
            return;
        }
        if (mHashSet.contains(getContentIdKey(params.content_id))) {
            return;
        }
        mHashSet.add(getContentIdKey(params.content_id));
        mBookService.getChapterContent(params)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<ChapterBean>() {
                    @Override
                    public void onNext(BaseResult<ChapterBean> tBaseResult) {
                        if (tBaseResult.result != null && tBaseResult.result.status != null) {
                            onResponse(tBaseResult, tBaseResult.result.data, mDisposable);
                        } else {
                            onError(Constants.ErrCode.NoData, "no data");
                        }
                        AndroidSchedulers.mainThread().scheduleDirect(() -> mHashSet.remove(getContentIdKey(params.content_id)), 500, TimeUnit.MILLISECONDS);
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        AndroidSchedulers.mainThread().scheduleDirect(() -> mHashSet.remove(getContentIdKey(params.content_id)), 500, TimeUnit.MILLISECONDS);
                        if (mDisposable.isDisposed()) {
                            return;
                        }
                        if (mView != null) {
                            mView.showError(params.content_id, code, errDesc);
                        }
                    }

                    @Override
                    public void onResponse(BaseResult<ChapterBean> info, ChapterBean userBean, Disposable disposable) {
                        if (mDisposable.isDisposed()) {
                            return;
                        }
                        if (BaseResult.isNotNull(info)) {
                            if (mView != null) {
                                mView.showContent(info, loadType);
                            }
                        }
                    }
                });
    }

    @Override
    public void getSimpleChapterInfo(String book_id, String order, INetCommCallback<SimpleChapterBean> callback) {
        if (!NetUtils.isNetworkAvailable(Xutils.getContext())) {
            if (callback != null) {
                callback.onError(Constants.ErrCode.NetErr, "no net");
            }
            return;
        }
        mBookService.getSimpleChapterInfo(book_id, order)
                .compose(asyncRequest())
                .subscribe(new BaseObserver<SimpleChapterBean>() {
                    @Override
                    public void onResponse(BaseResult<SimpleChapterBean> simpleChapterBeanBaseResult, SimpleChapterBean simpleChapterBean, Disposable disposable) {
                        if (callback != null) {
                            callback.onResponse(simpleChapterBean);
                        }
                    }

                    @Override
                    public void onError(int code, String errDesc) {
                        super.onError(code, errDesc);
                        if (callback != null) {
                            callback.onError(code, errDesc);
                        }
                    }
                });
    }

    @Override
    public void upLoadUserReadaction(String bookId, String contentId, int pageNum, long readConsumeTime) {
        mBookService.upLoadUserReadaction(bookId, contentId, String.valueOf(pageNum), String.valueOf(readConsumeTime / 1000)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                Log.d("upLoadUserReadaction", "onResponse: " + response);
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                Log.d("upLoadUserReadaction", "onFailure: " + throwable.toString());
            }
        });
    }

    @Override
    public void detachView() {
        super.detachView();
        if (mChapterSub != null) {
            mChapterSub.cancel();
        }

    }

}
